package com.miaoshaoproject.service.impl;

import com.miaoshaoproject.dao.UserDOMapper;
import com.miaoshaoproject.dao.UserPasswordDOMapper;
import com.miaoshaoproject.dataobject.UserDO;
import com.miaoshaoproject.dataobject.UserPasswordDO;
import com.miaoshaoproject.error.BussinessException;
import com.miaoshaoproject.error.EmBussinessError;
import com.miaoshaoproject.service.model.UserModel;
import com.miaoshaoproject.service.UserService;
import com.miaoshaoproject.validate.ValidationResult;
import com.miaoshaoproject.validate.ValidatorImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserDOMapper userDOMapper;
    @Autowired
    private UserPasswordDOMapper userPasswordDOMapper;
    @Autowired
    private ValidatorImpl validator;
    @Override
    public UserModel getUserById(Integer id) {
        UserDO userDO=userDOMapper.selectByPrimaryKey(id);
        if(userDO==null){
            return  null;
        }
        UserPasswordDO userPasswordDO=userPasswordDOMapper.selectByUserId(id);

       return  convertFromDataObject(userDO,userPasswordDO);

    }


    private UserModel convertFromDataObject(UserDO userDO, UserPasswordDO userPasswordDO){
        if(userDO==null){
            return  null;
        }
        UserModel userModel=new UserModel();
        BeanUtils.copyProperties(userDO,userModel);
        if(userPasswordDO!=null){
            userModel.setEncrptPassword(userPasswordDO.getEncrptPassword());
        }
        return userModel;
    }

    @Override
    @Transactional
    public void register(UserModel userModel) throws BussinessException {
           if(userModel==null){
               throw new BussinessException(EmBussinessError.PARAMETER_VALIDATION_ERROR);
           }
         /*  if(StringUtils.isEmpty(userModel.getName())
                ||StringUtils.isEmpty(userModel.getTelphone())
                ||userModel.getGender()==null
                ||userModel.getAge()==null){
            throw new BussinessException(EmBussinessError.PARAMETER_VALIDATION_ERROR);
           }*/
           ValidationResult result=validator.validate(userModel);
           if (result.isHasErrors()){
               throw new BussinessException(EmBussinessError.PARAMETER_VALIDATION_ERROR,result.getErrMsg());
           }
           //实现model --》dataobject方法
           UserDO userDO=convertFromMode(userModel);
        try {
            userDOMapper.insertSelective(userDO);
        } catch (DuplicateKeyException e) {
            throw new BussinessException(EmBussinessError.PARAMETER_VALIDATION_ERROR,"手机号已注册");
        }
        userModel.setId(userDO.getId());
        UserPasswordDO userPasswordDO=convertPassWordFromMode(userModel);
           userPasswordDOMapper.insertSelective(userPasswordDO);
           return  ;

    }



    private UserDO convertFromMode(UserModel userModel){
        if(userModel==null){
            return null;
        }
        UserDO userDO=new UserDO();
        BeanUtils.copyProperties(userModel,userDO);
        return userDO;
    }

    private UserPasswordDO convertPassWordFromMode(UserModel userModel){
        if(userModel==null){
            return null;
        }
        UserPasswordDO userPasswordDO=new UserPasswordDO();
        userPasswordDO.setEncrptPassword(userModel.getEncrptPassword());
        userPasswordDO.setUserId(userModel.getId());
        return userPasswordDO;
    }

    @Override
    public UserModel validateLogin(String telphone, String entryPassword) throws BussinessException {

        //通过用户的手机获取用户信息
        UserDO userDO=userDOMapper.selectByTelphone(telphone);
        if (userDO==null){
            throw new BussinessException(EmBussinessError.USER_LOGIN_FAIL);
        }
        UserPasswordDO userPasswordDO=userPasswordDOMapper.selectByUserId(userDO.getId());
        UserModel userModel=convertFromDataObject(userDO,userPasswordDO);
        //比对用户信息内加密的密码是否和传输进来的密码相匹配
        if(!StringUtils.endsWith(entryPassword,userModel.getEncrptPassword())){
            throw new BussinessException(EmBussinessError.PARAMETER_VALIDATION_ERROR);
        }
        return userModel;
    }

    @Override
    public UserModel getUserModelByIdInCache(Integer id) {
        UserModel userModel= (UserModel) redisTemplate.opsForValue().get("user_validate_"+id);
        if(userModel==null){
            userModel=this.getUserById(id);
            redisTemplate.opsForValue().set("user_validate_"+id,userModel);
            redisTemplate.expire("user_validate_"+id,10,TimeUnit.MINUTES);
        }
        return userModel;
    }


}
